//
//  NewFeatureCollectionViewController.swift
//  仿一个新浪微博
//
//  Created by 孙家林 on 15/9/18.
//  Copyright © 2015年 sunjialin. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class NewFeatureCollectionViewController: UICollectionViewController {
    
    //图片总数
    private let imageCount = 4
    
    //布局属性
    private let layout = HMFlowLayout()
    
    // 没有 override，因为 collectionView 的指定的构造函数是带 layout 的
    init() {
        
        super.init(collectionViewLayout: layout)
        
    }

    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
        
        super.init(coder: aDecoder)
    }
    
    

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }
    
    // 1. 获取数据源，确认有 cell
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return imageCount
    }
    
    // 3. 获取每个索引对应的cell
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell
    
        cell.imageIndex = indexPath.item
    
        return cell
    }
    
    // 完成显示 cell - indexPath 是之前消失 cell 的 indexPath
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        //获取当前显示的indexPath
        let path = collectionView.indexPathsForVisibleItems().last!
        
        //判断是否是末尾的indexPath
        if path.item == imageCount - 1 {
            
            //播放动画
            let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
            
            cell.startButoonAnim()
        }
    }
}

//新特性的自定义cell
class NewFeatureCell:UICollectionViewCell {
    
    private var imageIndex: Int = 0 {
        
        didSet {
            
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            startButton.hidden = true
        }
    }
    
    func clickStartButton() {
        
        NSNotificationCenter.defaultCenter().postNotificationName(HMRootViewControllerSwitchNotification, object: true)
    }
    
    //开始按钮动画
    private func startButoonAnim() {
    
        startButton.hidden = false
        
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        //禁止用户点击
        startButton.userInteractionEnabled = false
        
        UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            
                //恢复默认形变
                self.startButton.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                
                //启用按钮
                self.startButton.userInteractionEnabled = true
        }
    }

    override init(frame:CGRect) {
        
        super.init(frame: frame)
        
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        
        super.init(coder:aDecoder)
        
        prepareUI()
    }
    
    
    private func prepareUI() {
        
        //添加控件
        contentView.addSubview(iconView)
        contentView.addSubview(startButton)
        
        //自动布局
//        iconView.translatesAutoresizingMaskIntoConstraints = false
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview":iconView]))
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview":iconView]))
        
        iconView.ff_Fill(contentView)
        
//        startButton.translatesAutoresizingMaskIntoConstraints = false
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
        
        startButton.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160))
        
    }
    
    //懒加载控件
    private lazy var iconView = UIImageView()
    private lazy var startButton: UIButton = {
        
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.setTitle("开始体验", forState: UIControlState.Normal)
        
        button.sizeToFit()
        
        button.addTarget(self, action: "clickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
}
    
//自定义流水布局
private class HMFlowLayout:UICollectionViewFlowLayout {
        
        // 2. 如果还没有设置 layout，获取数量之后，准备cell之前，会被调用一次
        // 准备布局属性
    override private func prepareLayout() {
        
        itemSize = collectionView!.bounds.size
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.bounces = false
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
            
    }
}

